//
//  XXWeakMutableArray.m
//  dyss_v2
//
//  Created by LXF on 16/3/2.
//  Copyright © 2016年 First Facility. All rights reserved.
//

#import "NSMutableSet+XXWeakMutableSet.h"

@implementation NSMutableSet(XXWeakMutableSet)

-(void)xx_enumerateObjectsUsingBlock:(void (^)(id _Nonnull, BOOL * _Nonnull))block{
    [self xx_clearNilValue];
    [self.copy enumerateObjectsUsingBlock:^(id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[WeakRefNode class]]) {
            block([((WeakRefNode *)obj) value],stop);
        }else{
            block(obj,stop);
        }
    }];
}

-(void)xx_clearNilValue{
    NSMutableSet *tempSet = self.copy;
    for (id node in tempSet) {
        if ([node isKindOfClass:[WeakRefNode class]]) {
            if (((WeakRefNode *)node).isNil) {
                [self removeObject:node];
            }
        }
    }
}

-(id)xx_anyObject{
    WeakRefNode *node = [super anyObject];
    return node.value;
}

-(void)xx_addObject:(id)anObject{
    if (self.count > 100) {
        [self xx_clearNilValue];
    }
    [self addObject:[WeakRefNode node:anObject]];
}

- (void)xx_insertObject:(id)anObject {
    [self addObject:[WeakRefNode node:anObject]];
}

-(void)xx_removeObject:(id)object{
    [self removeObject:[WeakRefNode node:object]];
}

-(void)xx_addObjectsFromArray:(NSArray *)otherArray{
    for (id node in otherArray) {
        if ([node isKindOfClass:[WeakRefNode class]]) {
            [self addObject:node];
        }else{
            [self xx_addObject:node];
        }
    }
}

//-(BOOL)containsObject:(id)anObject{
//
//}

@end


@implementation WeakRefNode

+(instancetype)node:(id)anObject{
    WeakRefNode *node = [self new];
    
    node.value = anObject;
    
    return node;
}

-(NSUInteger)hash{
    if (self.value == nil) {
        return 0;
    }
    return [self.value hash];
}

-(BOOL)isNil{
    return self.value == nil;
}

-(BOOL)isEqual:(WeakRefNode *)object{
    if (object == nil) {
        return NO;
    }
    if (object == self) {
        return YES;
    }
    if ([object class] != [self class]) {
        return [self.value isEqual:object];
        return NO;
    }
    if (self.value == nil && [object value] == nil) {
        return YES;
    }
    return [self.value isEqual:object.value];
}

@end